<template>
  <div class="user-list-container">
    <!-- 页面标题和统计信息 -->
    <div class="dashboard-header">
      <div class="header-left">
        <h2 class="page-title">用户管理</h2>
        <p class="page-subtitle">管理系统中的所有用户账户和权限</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleAdd" class="add-button">
          <el-icon><Plus /></el-icon>添加用户
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stats-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>总用户数</span>
            <el-icon class="card-icon"><User /></el-icon>
          </div>
        </template>
        <div class="card-value">{{ total }}</div>
        <div class="card-trend">较上月 <span class="trend-up">+5%</span></div>
      </el-card>
      
      <el-card class="stats-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>活跃用户</span>
            <el-icon class="card-icon"><UserFilled /></el-icon>
          </div>
        </template>
        <div class="card-value">{{ userList.filter(u => u.status === 1).length }}</div>
        <div class="card-trend">较上月 <span class="trend-up">+3%</span></div>
      </el-card>
      
      <el-card class="stats-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>管理员数</span>
            <el-icon class="card-icon"><Avatar /></el-icon>
          </div>
        </template>
        <div class="card-value">{{ userList.filter(u => u.roles.includes('超级管理员')).length }}</div>
        <div class="card-trend">较上月 <span class="trend-stable">0%</span></div>
      </el-card>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card" shadow="hover">
      <div class="filter-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名或邮箱"
          class="search-input"
          clearable
          prefix-icon="Search"
        />
        <el-select v-model="statusFilter" placeholder="状态筛选" class="filter-select">
          <el-option label="全部" value="" />
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <el-select v-model="roleFilter" placeholder="角色筛选" class="filter-select">
          <el-option label="全部" value="" />
          <el-option label="超级管理员" value="超级管理员" />
          <el-option label="普通用户" value="普通用户" />
          <el-option label="编辑" value="编辑" />
        </el-select>
        <el-button type="primary" @click="handleFilter">筛选</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </div>
    </el-card>

    <!-- 用户表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table 
        :data="filteredUserList" 
        border 
        style="width: 100%" 
        v-loading="loading"
        :header-cell-style="{backgroundColor: '#f5f7fa'}"
        row-key="id"
        stripe
        highlight-current-row
      >
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="username" label="用户名" width="150" sortable />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="roles" label="角色" width="200">
          <template #default="{row}">
            <el-tag 
              v-for="role in row.roles" 
              :key="role" 
              style="margin-right: 5px"
              :type="getTagType(role)"
              effect="light"
              round
            >
              {{ role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" sortable />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{row}">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="(val) => handleStatusChange(row, val)"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="{row}">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button type="warning" size="small" @click="handleAssignRole(row)">
              <el-icon><SetUp /></el-icon> 角色
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="600px"
      destroy-on-close
    >
      <el-form :model="userForm" label-width="100px" :rules="rules" ref="userFormRef" class="user-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入用户名" prefix-icon="User" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" prefix-icon="Message" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
              <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password prefix-icon="Lock" />
            </el-form-item>
            <el-form-item label="部门" prop="department" v-else>
              <el-select v-model="userForm.department" placeholder="请选择部门" style="width: 100%">
                <el-option label="技术部" value="技术部" />
                <el-option label="市场部" value="市场部" />
                <el-option label="内容部" value="内容部" />
                <el-option label="人事部" value="人事部" />
                <el-option label="财务部" value="财务部" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="department" v-if="dialogType === 'add'">
              <el-select v-model="userForm.department" placeholder="请选择部门" style="width: 100%">
                <el-option label="技术部" value="技术部" />
                <el-option label="市场部" value="市场部" />
                <el-option label="内容部" value="内容部" />
                <el-option label="人事部" value="人事部" />
                <el-option label="财务部" value="财务部" />
              </el-select>
            </el-form-item>
            <el-form-item label="用户类型" prop="user_type" v-else>
              <el-select v-model="userForm.user_type" placeholder="请选择用户类型" style="width: 100%">
                <el-option label="学生" value="student" />
                <el-option label="教师" value="teacher" />
                <el-option label="职员" value="staff" />
                <el-option label="管理员" value="admin" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12" v-if="dialogType === 'add'">
            <el-form-item label="用户类型" prop="user_type">
              <el-select v-model="userForm.user_type" placeholder="请选择用户类型" style="width: 100%">
                <el-option label="学生" value="student" />
                <el-option label="教师" value="teacher" />
                <el-option label="职员" value="staff" />
                <el-option label="管理员" value="admin" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="dialogType === 'add' ? 12 : 24">
            <el-form-item label="状态">
              <el-switch
                v-model="userForm.status"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
                inline-prompt
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" plain>取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ dialogType === 'add' ? '创建' : '更新' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 角色分配对话框 -->
<el-dialog v-model="roleDialogVisible" title="分配角色" width="650px" destroy-on-close>
  <div class="role-dialog-content">
    <!-- 用户信息卡片 -->
    <div class="user-info-card" v-if="currentUser">
      <div class="user-avatar">
        <el-avatar :size="64" :icon="UserFilled" />
      </div>
      <div class="user-details">
        <h3>{{ currentUser.username }}</h3>
        <p><el-icon><Message /></el-icon> {{ currentUser.email }}</p>
        <p><el-icon><Avatar /></el-icon> {{ currentUser.department }}</p>
        <div class="user-roles">
          <el-tag 
            v-for="role in currentUser.roles" 
            :key="role"
            :type="getRoleTagType(role)"
            class="role-tag"
            size="small"
          >
            {{ role }}
          </el-tag>
        </div>
      </div>
    </div>

    <!-- 角色选择 -->
    <div class="role-selection">
      <div class="section-header">
        <h4>角色分配</h4>
        <span class="role-count">已选择 {{ selectedRoles.length }} 个角色</span>
      </div>
      
      <el-transfer
        v-model="selectedRoles"
        :data="allRoles"
        :titles="['可选角色', '已选角色']"
        filterable
        :props="{
          key: 'key',
          label: 'label'
        }"
      >
        <template #default="{ option }">
          <div class="role-item">
            <span>{{ option.label }}</span>
            <el-tag size="small" :type="getRoleTagType(option.label)" effect="plain">
              {{ getRoleDescription(option.label) }}
            </el-tag>
          </div>
        </template>
      </el-transfer>
    </div>

    <!-- 权限预览 -->
    <div class="permissions-preview">
      <div class="section-header">
        <h4>权限预览</h4>
        <span class="permission-count">共 {{ getSelectedRolePermissions().length }} 项权限</span>
      </div>
      <div class="permissions-list">
        <el-tag
          v-for="permission in getSelectedRolePermissions()"
          :key="permission"
          class="permission-tag"
          effect="plain"
        >
          {{ permission }}
        </el-tag>
        <div v-if="getSelectedRolePermissions().length === 0" class="no-permissions">
          未选择任何角色，无权限
        </div>
      </div>
    </div>
  </div>
  
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="roleDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitRoleAssign" :loading="submittingRoles">
        确认分配
      </el-button>
    </span>
  </template>
</el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, SetUp, User, UserFilled, Avatar, Search, Message, Lock } from '@element-plus/icons-vue'

// 表格数据
const loading = ref(false)
const userList = ref([
  {
    id: 1,
    username: 'admin',
    email: 'admin@example.com',
    roles: ['超级管理员'],
    createTime: '2023-01-01 12:00:00',
    status: 1,
    department: '技术部',
    lastLogin: '2023-07-15 08:30:22'
  },
  {
    id: 2,
    username: 'user1',
    email: 'user1@example.com',
    roles: ['普通用户'],
    createTime: '2023-01-02 10:30:00',
    status: 1,
    department: '市场部',
    lastLogin: '2023-07-14 16:45:10'
  },
  {
    id: 3,
    username: 'editor',
    email: 'editor@example.com',
    roles: ['编辑'],
    createTime: '2023-01-03 09:15:00',
    status: 0,
    department: '内容部',
    lastLogin: '2023-07-10 11:20:35'
  },
  {
    id: 4,
    username: 'guest',
    email: 'guest@example.com',
    roles: ['访客'],
    createTime: '2023-02-05 14:22:00',
    status: 1,
    department: '市场部',
    lastLogin: '2023-07-12 09:15:42'
  }
])

// 搜索和筛选
const searchQuery = ref('')
const statusFilter = ref('')
const roleFilter = ref('')

// 筛选后的用户列表
const filteredUserList = computed(() => {
  let result = [...userList.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(user => 
      user.username.toLowerCase().includes(query) || 
      user.email.toLowerCase().includes(query)
    )
  }
  
  // 状态过滤
  if (statusFilter.value !== '') {
    result = result.filter(user => user.status === statusFilter.value)
  }
  
  // 角色过滤
  if (roleFilter.value) {
    result = result.filter(user => 
      user.roles.includes(roleFilter.value)
    )
  }
  
  return result
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(4) // 更新为4个用户

const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchData()
}

// 表单对话框
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const submitting = ref(false)
const userForm = reactive({
  id: 0,
  username: '',
  email: '',
  password: '',
  status: 1,
  department: '',
  user_type: 'staff'
})
const userFormRef = ref()

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ]
}

// 角色分配对话框
const roleDialogVisible = ref(false)
const currentUserId = ref(0)
const currentUser = ref<any>(null)
const submittingRoles = ref(false)
const allRoles = ref([
  { key: 1, label: '超级管理员' },
  { key: 2, label: '普通用户' },
  { key: 3, label: '编辑' },
  { key: 4, label: '访客' }
])
const selectedRoles = ref<number[]>([])

// 角色权限映射
const rolePermissionsMap = {
  '超级管理员': ['用户管理', '角色管理', '权限管理', '系统设置', '数据导出', '数据导入', '日志查看'],
  '普通用户': ['个人信息查看', '个人信息编辑', '数据查看'],
  '编辑': ['内容管理', '内容编辑', '内容审核', '评论管理'],
  '访客': ['内容查看']
}

// 方法
const fetchData = () => {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const resetForm = () => {
  userForm.id = 0
  userForm.username = ''
  userForm.email = ''
  userForm.password = ''
  userForm.status = 1
  userForm.department = ''
  userForm.user_type = 'staff'
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 根据角色返回不同的标签类型
const getTagType = (role: string) => {
  switch (role) {
    case '超级管理员':
      return 'danger'
    case '普通用户':
      return 'success'
    case '编辑':
      return 'warning'
    case '访客':
      return 'info'
    default:
      return ''
  }
}

// 根据角色返回不同的标签类型（用于角色分配对话框）
const getRoleTagType = (role: string) => {
  switch (role) {
    case '超级管理员':
      return 'danger'
    case '普通用户':
      return 'success'
    case '编辑':
      return 'warning'
    case '访客':
      return 'info'
    default:
      return ''
  }
}

// 获取角色描述
const getRoleDescription = (role: string) => {
  switch (role) {
    case '超级管理员':
      return '所有权限'
    case '普通用户':
      return '基础权限'
    case '编辑':
      return '内容管理'
    case '访客':
      return '只读权限'
    default:
      return ''
  }
}

// 获取选中角色的权限
const getSelectedRolePermissions = () => {
  const permissions = new Set<string>()
  selectedRoles.value.forEach(roleId => {
    const roleName = allRoles.value.find(r => r.key === roleId)?.label || ''
    if (roleName && rolePermissionsMap[roleName]) {
      rolePermissionsMap[roleName].forEach(perm => permissions.add(perm))
    }
  })
  return Array.from(permissions)
}

// 处理状态变更
const handleStatusChange = (row: any, val: number) => {
  const statusText = val === 1 ? '启用' : '禁用'
  ElMessage.success(`已${statusText}用户: ${row.username}`)
  // 这里可以调用API更新用户状态
}

// 处理筛选
const handleFilter = () => {
  // 筛选逻辑已通过计算属性实现
  currentPage.value = 1 // 重置到第一页
}

// 重置筛选
const resetFilter = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  roleFilter.value = ''
  currentPage.value = 1
}

const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  Object.assign(userForm, row)
  dialogVisible.value = true
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除用户 ${row.username} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    ElMessage.success('删除成功')
    fetchData()
  }).catch(() => {})
}

const submitForm = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      submitting.value = true
      // 模拟API请求
      setTimeout(() => {
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
        submitting.value = false
        fetchData()
      }, 800)
    }
  })
}

const handleAssignRole = (row: any) => {
  currentUserId.value = row.id
  currentUser.value = row
  // 根据用户已有角色设置选中项
  selectedRoles.value = row.roles.includes('超级管理员') ? [1] : 
                        row.roles.includes('普通用户') ? [2] : 
                        row.roles.includes('编辑') ? [3] : 
                        row.roles.includes('访客') ? [4] : []
  roleDialogVisible.value = true
}

const submitRoleAssign = () => {
  submittingRoles.value = true
  // 模拟API请求
  setTimeout(() => {
    // 更新用户的角色
    const user = userList.value.find(u => u.id === currentUserId.value)
    if (user) {
      user.roles = selectedRoles.value.map(roleId => {
        const role = allRoles.value.find(r => r.key === roleId)
        return role ? role.label : ''
      }).filter(label => label !== '')
    }
    
    ElMessage.success('角色分配成功')
    roleDialogVisible.value = false
    submittingRoles.value = false
    fetchData()
  }, 800)
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
/* 主容器样式 */
.user-list-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

/* 仪表盘头部样式 */
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-left {
  display: flex;
  flex-direction: column;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 8px 0 0;
  font-size: 14px;
  color: #909399;
}

.add-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 统计卡片样式 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stats-card {
  border-radius: 8px;
  transition: transform 0.3s, box-shadow 0.3s;
}

.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  color: #606266;
}

.card-icon {
  font-size: 20px;
  color: #409EFF;
}

.card-value {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin: 16px 0 8px;
}

.card-trend {
  font-size: 14px;
  color: #909399;
}

.trend-up {
  color: #67C23A;
}

.trend-down {
  color: #F56C6C;
}

.trend-stable {
  color: #E6A23C;
}

/* 筛选卡片样式 */
.filter-card {
  margin-bottom: 24px;
  border-radius: 8px;
}

.filter-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.search-input {
  width: 240px;
}

.filter-select {
  width: 160px;
}

/* 表格卡片样式 */
.table-card {
  border-radius: 8px;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 角色分配对话框样式 */
.role-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.user-info-card {
  display: flex;
  gap: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 8px;
}

.user-avatar {
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-details {
  flex: 1;
}

.user-details h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.user-details p {
  margin: 4px 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.user-roles {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.role-tag {
  margin-right: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.role-count, .permission-count {
  font-size: 14px;
  color: #909399;
}

.role-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 4px 0;
}

.permissions-preview {
  margin-top: 8px;
}

.permissions-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  min-height: 60px;
}

.permission-tag {
  margin-right: 0;
}

.no-permissions {
  width: 100%;
  text-align: center;
  color: #909399;
  font-size: 14px;
  padding: 16px 0;
}

/* 用户表单样式 */
.user-form .form-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.user-form .form-col {
  flex: 1;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .filter-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .filter-select {
    width: 100%;
  }
  
  .user-form .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .role-dialog-content {
    gap: 16px;
  }
}
</style>